<template>
  <div class="app-container">
    <hq-searchDown ref="hqSearchDown" :select-opts="selectOpts" @click="handleFilter" />
    <div class="filter-container">
      <span v-if="authorityHandle(123)" class="filter-title filter-item">身份所属</span>
      <k-select
        v-if="authorityHandle(123)"
        v-model="listQuery.userType"
        class="filter-item right-item"
        style="width:120px"
        :select-params="dict.type.IDENTITY_TYPE"
        @handleSelectEvent="$refs.hqSearchDown.searchFun()"
      />
      <span class="filter-title filter-item">饰品来源</span>
      <k-select
        v-model="listQuery.goodsOrigin"
        class="filter-item right-item"
        style="width:120px"
        :custom-params="{opations:originList, label:'lineName',value:'lineId'}"
        @handleSelectEvent="$refs.hqSearchDown.searchFun()"
      />
      <span class="filter-title filter-item">箱子名称</span>
      <k-select
        v-model="listQuery.boxId"
        class="filter-item right-item"
        style="width:120px"
        :custom-params="{opations:caseList, label:'lineName',value:'lineId'}"
        @handleSelectEvent="$refs.hqSearchDown.searchFun()"
      />
      <span class="filter-title filter-item">饰品状态</span>
      <k-select
        v-model="listQuery.goodsStatus"
        class="filter-item right-item"
        style="width:120px"
        :custom-params="{opations:goodsStatusList, label:'lineName',value:'lineId'}"
        @handleSelectEvent="$refs.hqSearchDown.searchFun()"
      />
      <span class="filter-title filter-item">开箱时间</span>
      <k-date-picker v-model="timeValue" class="filter-item" @hqchang="$refs.hqSearchDown.searchFun()" />
      <span class="filter-title filter-item">操作时间</span>
      <k-date-picker v-model="openBoxTimeValue" class="filter-item" @hqchang="$refs.hqSearchDown.searchFun()" />
    </div>
    <div v-if="authorityHandle(122)" class="top-right-btn-container">
      <k-button class="top-btn" value="放回背包" @click.native="putBagsBack"/>
      <k-button class="top-right-btn-left" value="饰品放入" @click.native="addBabyDialog"/>
      <k-button class="top-right-btn" value="饰品作废" @click.native="babyValidate" />
    </div>
    <div v-else style="margin-top: 40px;" />
    <!--表格相关 ="!authorityHandle(122)"-->
    <el-table
      ref="multipleTable"
      :data="listData"
      fit
      border
      :show-summary="!authorityHandle(459)"
      :summary-method="getSummaries"
      highlight-current-row
      style="width: 100%; border-radius: 8px; margin-top: 20px;"
      :header-cell-style="{ background: '#F6F5FA', color: '#4E4F62' }"
      @selection-change="handleSelectionChange"
      @sort-change="sortChange"
    >
      <el-table-column v-if="authorityHandle(122)" min-width="60px" type="selection" align="center" />
      <el-table-column prop="userName" min-width="100px" label="用户账号" show-overflow-tooltip />
      <el-table-column prop="userTypeName" min-width="100px" label="身份所属" show-overflow-tooltip />
      <el-table-column prop="goodsName" min-width="150px" label="饰品名称" show-overflow-tooltip />
      <el-table-column prop="goodsPrice" min-width="100px" label="饰品价值(J)" sortable="custom" show-overflow-tooltip />
      <el-table-column min-width="100px" label="饰品状态" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.goodsStatusName==='已出售'?'已兑换':scope.row.goodsStatusName }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="goodsOriginName" min-width="100px" label="饰品来源" show-overflow-tooltip />
      <el-table-column prop="boxName" min-width="100px" label="箱子名称" show-overflow-tooltip />
      <el-table-column prop="getTime" min-width="120px" label="获得时间" sortable="custom" show-overflow-tooltip />
      <el-table-column prop="operationTime" min-width="120px" label="操作时间" sortable="custom" show-overflow-tooltip />
      <el-table-column prop="rucksackId" min-width="100px" label="ID" show-overflow-tooltip />
    </el-table>
    <pagination
      v-show="totalRows > 0"
      :total="totalRows"
      :page.sync="listQuery.pager.pageNo"
      :limit.sync="listQuery.pager.pageSize"
      @pagination="$refs.hqSearchDown.searchFun(1)"
    />
    <!-- 饰品放入 弹窗 -->
    <k-dialog
      :show-hide.sync="addBaby"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="饰品放入"
      class="addBox_dialog"
      :two-btn="true"
      :close-fun="handleCloseDialog"
      @click="saveBabyEvent"
    >
      <el-form label-width="auto" class="form_content">
        <el-form-item label="用户名：">
          <search-select
            ref="KsearchSelect"
            :result-list="userResultList"
            @requestReslutList="requestUserReslutList"
            @selectChange="selectUserChange"
            @visibleChange="visibleUserChange"
          />
        </el-form-item>
        <el-form-item label="饰品名称：">
          <search-select-common
            ref="KsearchSelectCommon"
            :result-list="goodsResultList"
            @requestReslutList="requestGoodsReslutList"
            @selectChange="selectGoodsChange"
            @visibleChange="visibleGoodsChange"
          />
        </el-form-item>
      </el-form>
    </k-dialog>
  </div>
</template>

<script>
import { listData, initGoods, abolishGoods, getOriginList, getGoodsStatus, getBoxListByOriginList, addGoods } from '@/api/data/data'
import { getGoodsPlatformList } from '@/api/rules/listdata'
import { getAllWebUser } from '@/api/red/data'
import { getOrnamentGlobalValue } from '@/api/data/data'
import hqSearchDown from '@/components/hqSearchDown' // 下拉搜索
import Pagination from '@/components/Pagination'
import SearchSelect from '@/components/SearchSelect'
import SearchSelectCommon from '@/components/SearchSelectCommon'

export default {
  components: { Pagination, SearchSelect, SearchSelectCommon, hqSearchDown },
  dicts: ['IDENTITY_TYPE'],
  data() {
    return {
      // 下拉搜索项0
      selectOpts: [
        {
          label: '用户账号',
          rigth: true,
          value: 'userName'
        }, {
          label: '饰品名称',
          value: 'goodsName'
        }, {
          label: '箱子名称',
          value: 'boxName'
        }
      ],
      addBaby: false,
      listData: [],
      originList: [],
      caseList: [],
      goodsStatusList: [],
      multipleSelection: [],
      // 操作时间
      timeValue: '',
      // 开箱时间
      openBoxTimeValue: '',
      totalRows: 0, // 分页组件--数据总条数
      listQuery: {
        pager: {
          pageNo: 1,
          pageSize: 10,
          totalRows: '',
          start: ''
        },
        sort: '', // 排序字段 为对应列名,
        direction: '', // 排序 正向(asc)逆向(desc),
        userType: undefined, // 用户类型",
        goodsOrigin: undefined, // 饰品来源",
        boxId: undefined, // 箱子id",
        goodsStatus: undefined, // 饰品状态",
        getTimeStart: '', // 开始时间",
        getTimeEnd: '', // 结束时间",
        key: '', // 饰品名称'
        operationTimeStart: '',
        operationTimeEnd: ''
      },
      checkedUserIdList: [],
      userResultList: [],
      checkedGoodsIdList: [],
      goodsResultList: [],
      // 价值
      goodsPrice: '',
      paramData: {}

    }
  },
  computed: {},
  watch: {
    // 时间赋值 新
    timeValue(val) {
      this.listQuery.getTimeStart = this.timeValue ? this.timeValue[0] : null
      this.listQuery.getTimeEnd = this.timeValue ? this.timeValue[1] : null
    },
    // 时间
    openBoxTimeValue(val) {
      this.listQuery.operationTimeStart = this.openBoxTimeValue ? this.openBoxTimeValue[0] : null
      this.listQuery.operationTimeEnd = this.openBoxTimeValue ? this.openBoxTimeValue[1] : null
    }
  },
  created() {
    this.loadData()
    this.getOriginList()
    this.getGoodsStatus()
    this.tableDate()
  },

  methods: {
    /**
     * 合计
     * @param {obj} param
     */
    getSummaries(param) {
      const { columns } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) { // 第一列
          sums[index] = '总计'
        } else if (column.property === 'goodsPrice') {
          sums[index] = ''
        }
      })
      return sums
    },
    loadData(v) {
      this.paramData = {}
      this.paramData = { ...v, ...this.listQuery }
      listData(this.paramData).then(res => {
        const data = res.data
        this.listData = data.rows
        this.totalRows = data.totalRows
        if (this.goodsPrice) {
          this.goodsPrice = ''
          this.tableDate()
        }
      })
    },
    tableDate() {
      if (!this.authorityHandle(201)) return
      this.$nextTick(() => {
        let html4
        if (this.authorityHandle(122)) {
          html4 = this.$refs.multipleTable.$refs.footerWrapper.querySelector('.el-table__footer')
            .querySelectorAll('td')[4]
            .querySelector('.cell')
        } else {
          html4 = this.$refs.multipleTable.$refs.footerWrapper.querySelector('.el-table__footer')
            .querySelectorAll('td')[3]
            .querySelector('.cell')
        }
        html4.innerHTML = `${this.goodsPrice !== '' ? this.goodsPrice : ''} <a  style="text-decoration: underline;color: blue"><i class="el-icon-refresh"></i></a>`
        html4.onclick = () => {
          getOrnamentGlobalValue({ ...this.paramData }).then(res => {
            this.goodsPrice = res.data
            this.tableDate()
          })
        }
      })
    },
    handleCloseDialog() {
      this.addBaby = false
      this.$nextTick(() => {
        this.checkedUserIdList = []
        this.checkedGoodsIdList = []
        this.$refs.KsearchSelect.checkedList = []
        this.$refs.KsearchSelect.selectValueList = []
        this.$refs.KsearchSelectCommon.checkedList = []
        this.$refs.KsearchSelectCommon.selectValueList = []
      })
    },
    addBabyDialog() {
      this.addBaby = true
    },
    // 请求推广用户返回列表
    requestUserReslutList(value) {
      getAllWebUser({ key: value }).then(res => {
        this.userResultList = []
        Object.assign(this.userResultList, res.data)
        this.userResultList = this.userResultList.filter(item => !this.checkedUserIdList.includes(item.id))
      })
    },
    requestGoodsReslutList(value) {
      getGoodsPlatformList({ key: value, alreadyIds: '[-1]' }).then(res => {
        this.goodsResultList = []
        Object.assign(this.goodsResultList, res.data)
        this.goodsResultList = this.goodsResultList.filter(item => !this.checkedGoodsIdList.includes(item.lineId))
      })
    },
    selectUserChange(checkedUserIdList) {
      this.checkedUserIdList = []
      this.checkedUserIdList = checkedUserIdList.map(item => {
        return item.id
      })
    },
    visibleUserChange() {
      this.userResultList = []
    },
    selectGoodsChange(checkedGoodsIdList) {
      this.checkedGoodsIdList = []
      this.checkedGoodsIdList = checkedGoodsIdList.map(item => {
        return item.lineId
      })
    },
    visibleGoodsChange() {
      this.goodsResultList = []
    },
    // 保存 AI数据
    saveBabyEvent() {
      if (this.checkedUserIdList.length < 1 || this.checkedGoodsIdList.length < 1) {
        this.$message.error('请选择用户或者饰品添加！')
        return
      }
      addGoods({ 'userIds': this.checkedUserIdList, 'goodsIds': this.checkedGoodsIdList }).then(res => {
        this.$message.success('保存成功')
        this.loadData()
      })
      this.handleCloseDialog()
      this.addBaby = false
    },
    getOriginList() {
      getOriginList().then(res => {
        this.$log(res)
        this.originList = res.data
      })
    },
    getGoodsStatus() {
      getGoodsStatus().then(res => {
        this.goodsStatusList = res.data
        this.goodsStatusList.map(function(item) {
          item.lineName = item.lineName === '已出售' ? '已兑换' : item.lineName
        })
      })
      getBoxListByOriginList().then(res => {
        this.caseList = res.data
      })
    },
    // 选择项发生变化时会触发该事件
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 表格的排序条件发生变化的时候会触发该事件
    sortChange(column, prop, order) {
      this.listQuery.sort = column.prop
      if (column.order === 'ascending') {
        this.listQuery.direction = 'asc'
      } else if (column.order === 'descending') {
        this.listQuery.direction = 'desc'
      }
      this.$refs.hqSearchDown.searchFun()
    },
    // 放回背包
    putBagsBack() {
      const _vue = this
      if (_vue.multipleSelection.length < 1) {
        this.$message.error('请至少选择一条数据进行操作！')
        return
      }
      const selections = _vue.multipleSelection
      this.$confirm('确定把选中的饰品放回背包么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var ids = []
        for (var i = 0; i < selections.length; i++) {
          ids.push(selections[i].id)
        }
        initGoods({ ids: ids }).then(res => {
          this.$message.success('放回成功')
          this.$refs.hqSearchDown.searchFun()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    // 饰品作废
    babyValidate() {
      const _vue = this
      if (_vue.multipleSelection.length < 1) {
        this.$message.error('请至少选择一条数据进行作废！')
        return
      }
      const selections = _vue.multipleSelection
      this.$confirm('确定作废选中的饰品么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var ids = []
        for (var i = 0; i < selections.length; i++) {
          ids.push(selections[i].id)
        }
        abolishGoods({ ids: ids }).then(res => {
          this.$message.success('作废成功')
          this.$refs.hqSearchDown.searchFun()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    // 搜索查询事件
    handleFilter(v, type) {
      if (type !== 1) {
        this.listQuery.pager.pageNo = 1
        this.$route.params.extensionId = undefined
      }
      this.loadData(v)
    }
  }
}
</script>
<style lang="scss" scoped>
$menuText: #14162E; // 侧边栏字体颜色
$hoverColor: #1D143C; // 鼠标停留主色调浅色
$mainColor: #3b425d; // 主色调

.filter-container {
  width: 100%;
  height: 48px;
  line-height: 48px;

  .filter-item {
    display: inline-block;
    vertical-align: middle;
    margin-bottom: 10px;
  }

  .kInput {
    position: absolute;
    right: 20px;
  }

  .filter-title {
    height: 48px;
    line-height: 48px;
    font-size: 16px;
    font-weight: 500;
    margin-right: 22px;
    color: #14162E;
  }

  .right-item {
    margin-right: 10px;
  }
}

.top-right-btn-container {
  position: relative;

  .top-btn {
    margin: 30px 20px 30px 0px;
    font-size: 14px;
    color: #ffffff;
  }

  .top-right-btn {
    position: absolute;
    right: 20px;
    top: 30px;
    background-color: #F8F7FB;
    border-color: $mainColor;
    color: #14162E;

    &:hover {
      color: #ffffff;
      background-color: $mainColor;
    }

    &:active {
      color: #14162E;
    }

  }

  .top-right-btn-left {
    position: absolute;
    right: 140px;
    top: 30px;
    background-color: #F8F7FB;
    border-color: $mainColor;
    color: #14162E;

    &:hover {
      color: #ffffff;
      background-color: $mainColor;
    }

    &:active {
      color: #14162E;
    }

  }
}

.el-message-box {
  .el-button {
    border: 1px solid #3b425d;
    color: #3b425d;
    background-color: rgba($color: #3b425d, $alpha: .1);
  }
}

.form_content {
  margin-bottom: 50px;
}

.addBox_dialog {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  ::v-deep .el-dialog__body {
    width: 678px;
    margin: 40px 80px;
  }

  ::v-deep .el-select .el-select__tags>span {
    display: none;
  }

  .el-tag+.el-tag {
    margin-left: 10px;
  }

  .el-tag {
    color: $mainColor;
    background-color: #ffffff;
    border-color: $mainColor;

    ::v-deep .el-tag__close {
      color: $mainColor;
    }

    ::v-deep .el-icon-close:hover {
      color: #ffffff;
      background: $mainColor;
    }
  }
}
</style>
